<template>
  <div>
    <admin-menu/>

    <!-- 主内容区域 -->
    <main class="ml-64 flex-1 p-6">

      <!-- 顶部标题栏 -->
      <header class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-semibold text-gray-800">系统首页</h1>
        <div class="flex items-center space-x-4">
          <i class="fas fa-cloud-sun text-2xl text-blue-400"></i>
          <p class="text-sm text-gray-500">{{ weather.city }}</p>
          <p class="text-xl font-bold">{{ weather.temp }}°C</p>

          <span class="text-gray-600" style="cursor:pointer;" @click="showerForecast">
            <i class="el-icon-link"></i> 友情链接
          </span>
          <!-- 通知按钮和弹窗 -->
          <el-popover
              v-model="popoverVisible"
              placement="bottom-end"
              popper-class="notification-popover"
              trigger="click"
              width="400"
          >
            <div class="notification-container">
              <div class="message-list">
                <div
                    v-for="(message, index) in currentPageMessages"
                    :key="index"
                    class="message-card hover:shadow-md"
                    @click="markAsRead(message)"
                >
                  <el-avatar :size="40" :src="message.YHZP" class="mr-3"/>
                  <div class="message-content">
                    <div class="message-header">
                      <span class="sender">{{ message.CFZXM }}</span>
                      <span class="time">{{ formatDate(message.CFSJ) }}</span>
                    </div>
                    <p>{{ message.DZNR }}</p>
                  </div>
                  <div v-if="!message.YDBZ" class="unread-dot"></div>
                </div>
              </div>
              <el-pagination
                  :current-page.sync="currentPage"
                  :page-size="pageSize"
                  :total="messages.length"
                  class="pagination"
                  layout="prev, pager, next"
                  @current-change="handlePageChange"
              />
            </div>

            <button slot="reference" class="hover:text-slate-600 relative">
              <i class="el-icon-bell text-xl"></i>
              <span
                  v-show="messages.some(msg => msg.YDBZ === 0)"
                  class="absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full"
              ></span>
            </button>
          </el-popover>
          <span class="text-gray-600">{{ UserInfo.role }}：{{ UserInfo.name }}</span>
          <button class="bg-red-500 text-white px-3 py-1 rounded hover:bg-red-600">
            退出登录
          </button>
        </div>
      </header>

      <!-- 统计卡片 -->
      <div class="grid grid-cols-5 gap-4 mb-6">
        <div class="bg-white border border-gray-100 p-4 rounded-lg shadow-sm stat-card">
          <div class="flex justify-between items-center">
            <div>
              <p class="text-gray-500">总学生数</p>
              <p class="text-2xl font-bold text-blue-600">{{ IndexDataCount.XSS }}</p>
            </div>
            <i class="fas fa-users text-blue-400"></i>
          </div>
        </div>
        <div class="bg-white border border-gray-100 p-4 rounded-lg shadow-sm stat-card">
          <div class="flex justify-between items-center">
            <div>
              <p class="text-gray-500">已就业学生</p>
              <p class="text-2xl font-bold text-green-600">{{ IndexDataCount.YJYXSS }}</p>
            </div>
            <i class="fas fa-check-circle text-green-400"></i>
          </div>
        </div>
        <div class="bg-white border border-gray-100 p-4 rounded-lg shadow-sm stat-card">
          <div class="flex justify-between items-center">
            <div>
              <p class="text-gray-500">就业率</p>
              <p class="text-2xl font-bold text-yellow-600">{{ IndexDataCount.JYL*100 }}%</p>
            </div>
            <i class="fas fa-trending-up text-yellow-400"></i>
          </div>
        </div>
        <div class="bg-white border border-gray-100 p-4 rounded-lg shadow-sm stat-card">
          <div class="flex justify-between items-center">
            <div>
              <p class="text-gray-500">合作企业</p>
              <p class="text-2xl font-bold text-purple-600">{{ IndexDataCount.RZDWS }}</p>
            </div>
            <i class="fas fa-building text-purple-400"></i>
          </div>
        </div>
        <div class="bg-white border border-gray-100 p-4 rounded-lg shadow-sm stat-card">
          <div class="flex justify-between items-center">
            <div>
              <p class="text-gray-500">岗位数量</p>
              <p class="text-2xl font-bold text-purple-600">{{ IndexDataCount.YXGWS }}</p>
            </div>
            <i class="fas fa-briefcase text-purple-400"></i>
          </div>
        </div>
      </div>

      <!-- 图表与新增模块 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">

        <!-- 各专业学生分布 -->
        <div class="bg-white border border-gray-100 p-4 rounded-lg shadow-sm chart-card hover:shadow-md">
          <h2 class="text-lg font-semibold mb-4">各专业学生分布</h2>
          <canvas id="majorStudentsChart" height="200" width="300"></canvas>
        </div>

        <!-- 学生就业趋势 -->
        <div class="bg-white border border-gray-100 p-4 rounded-lg shadow-sm chart-card hover:shadow-md">
          <h2 class="text-lg font-semibold mb-4">学生投递趋势</h2>
          <canvas id="employmentTrendChart" height="200" width="300"></canvas>
        </div>

        <!-- 就业行业分布 -->
        <div class="bg-white border border-gray-100 p-4 rounded-lg shadow-sm chart-card hover:shadow-md">
          <h2 class="text-lg font-semibold mb-4">就业行业分布</h2>
          <canvas id="industryDistributionChart" height="200" width="300"></canvas>
        </div>

        <!-- 面试场次统计 -->
        <div class="bg-white border border-gray-100 p-4 rounded-lg shadow-sm chart-card hover:shadow-md">
          <h2 class="text-lg font-semibold mb-4">面试场次统计</h2>
          <canvas id="interviewSessionsChart" height="200" width="300"></canvas>
        </div>

        <!-- 最新招聘信息 -->
        <div class="bg-white border border-gray-100 p-4 rounded-lg shadow-sm lg:col-span-2 hover:shadow-md">
          <h3 class="text-lg font-semibold mb-4">最新招聘信息</h3>
          <ul class="divide-y">
            <li
                v-for="(gw, index) in DATAGWDMK"
                :key="index"
                class="py-2 flex justify-between"
            >
              <span>{{ gw.GSMC }} - {{ gw.GWMC }}</span>
              <span class="text-gray-500">{{ formatDate(gw.FBSJ) }}</span>
            </li>
          </ul>
        </div>

        <!-- 今日待办事项 -->
        <div class="bg-white border border-gray-100 p-4 rounded-lg shadow-sm lg:col-span-2 hover:shadow-md">
          <h3 class="text-lg font-semibold mb-4">今日待办事项</h3>
          <ul class="divide-y">
            <li
                v-for="(task, index) in todoList"
                :key="index"
                class="py-2 flex justify-between"
            >
              <span>{{ task.title }}</span>
              <span class="text-gray-500">{{ task.time }}</span>
            </li>
          </ul>
        </div>
      </div>
      <el-dialog title="友情链接管理" :visible.sync="dialogVisible" width="800px">
        <!-- 表单区域 -->
        <el-form :model="form" ref="formRef" label-width="100px" style="margin-bottom: 20px">
          <el-form-item label="链接标题">
            <el-input v-model="form.ljbt" placeholder="请输入标题" />
          </el-form-item>
          <el-form-item label="链接地址">
            <el-input v-model="form.ljdz" placeholder="请输入URL" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">{{ form.id ? '更新' : '添加' }}</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 表格区域 -->
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column prop="id" label="ID" width="60" />
          <el-table-column prop="ljbt" label="标题" />
          <el-table-column prop="ljdz" label="地址">
            <template v-slot="scope">
              <a :href="scope.row.ljdz" target="_blank">
                {{ scope.row.ljdz.length > 30 ? scope.row.ljdz.slice(0, 30) + '...' : scope.row.ljdz }}
              </a>
            </template>
          </el-table-column>
          <el-table-column prop="tjsj" label="添加时间" width="160" />
          <el-table-column prop="tjr" label="添加人" width="100" />
          <el-table-column label="操作" width="180">
            <template v-slot="scope">
              <el-button size="mini" @click="editRow(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="deleteRow(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </main>
  </div>
</template>

<script>
import AdminMenu from "@/components/admin/Admin_menu.vue";
import {Chart, registerables} from "chart.js";
import ChartDataLabels from "chartjs-plugin-datalabels";
import axios from "axios";
import {EventBus} from "@/event-bus";

Chart.register(...registerables);
Chart.register(ChartDataLabels);

export default {
  name: "AdminIndex",
  components: {AdminMenu},
  data() {
    return {
      tableData: [],
      form: {
        id: null,
        ljbt: '',
        ljdz: '',
        tjsj: '',
        tjr: '',
        tjrsfdm: ''
      },
      dialogVisible:false,


      popoverVisible: false,
      messages: [],
      currentPage: 1,
      pageSize: 5,
      DATAGWDMK: [],
      todoList: [
        {title: "岗位审核", time: "10:00"},
        {title: "企业资质审核", time: "14:00"},
        {title: "查看面试统计", time: "16:00"},
      ],
      weather: {
        city: "上海",
        temp: 25,
      },
      IndexDataCount: {
        XSS: -1,
        RZDWS: -1,
        YJYXSS: -1,
        JYL: 0.0,
        YXGWS: -1,
      },
      UserInfo: {
        name: "",
        role: "",
        username: "",
      },
    };
  },
  computed: {
    currentPageMessages() {
      const start = (this.currentPage - 1) * this.pageSize;
      return this.messages.slice(start, start + this.pageSize);
    },
  },
  watch: {
    popoverVisible(val) {
      if (!val) {
        // 弹窗被关闭
        console.log('Popover 已关闭')
        this.handlePopoverClosed()
      }
    }
  },
  mounted() {
    this.getLoginUserInfo();
    this.initCharts();
  },
  methods: {
    showerForecast(){
      if (this.tableData.length===0){
        this.loadData();
      }
      this.dialogVisible = true;
    },
    async loadData() {
      try {
        const res = await axios.get("/yqljk/getAllYqljk");
        this.tableData = res.data.data;
      } catch (e) {
        console.error("加载数据失败", e);
      }
    },
    async submitForm() {
      try {
        const DataLj = new FormData();
        const isUpdate = !!this.form.id;

        // 公共字段
        DataLj.append('ljbt', this.form.ljbt);
        DataLj.append('ljdz', this.form.ljdz);


        if (isUpdate) {
          DataLj.append('id', this.form.id);
          await axios.post("/yqljk/updateYqljk", DataLj);
          this.$message.success("更新成功！");
        } else {
          DataLj.append('tjr', this.UserInfo.username); // 注意大小写
          DataLj.append('tjrsfdm', 1);
          await axios.post("/yqljk/addYqljk", DataLj);
          this.$message.success("添加成功！");
        }

        this.resetForm();
        this.loadData();
      } catch (e) {
        this.$message.error("提交失败！");
        console.error(e);
      }
    },

    editRow(row) {
      this.form = { ...row };
    },
    async deleteRow(id) {
      try {
        await this.$confirm("确定删除此链接吗？", "警告", { type: "warning" });
        await axios.get("/yqljk/deleteYqljk?id="+id);
        this.$message.success("删除成功！");
        this.loadData();
      } catch {
        this.$message.info("取消删除");
      }
    },
    resetForm() {
      this.form = {
        id: null,
        ljbt: '',
        ljdz: '',
        tjsj: '',
        tjr: '',
        tjrsfdm: ''
      };
    },
    handlePopoverClosed() {
      // 在这里写你想做的关闭逻辑，比如保存状态、刷新消息等
      axios.get("/xxdmk/setRead", {
        params: {
          YHM: this.UserInfo.username,
          YHSFDM: 1
        }
      }).then(response => {
        if (!response.data.result) {
          $.confirm({
            title: '⚠️ 系统崩溃警告',
            content: `<div style="color:#b00020;font-weight:bold;font-size:16px;">
                更新消息状态失败（灾难性故障）：
                <br><br>
                <code>${response.data.data}</code>
              </div>`,
            type: 'red',
            typeAnimated: true,
            boxWidth: '500px',
            useBootstrap: false, // 更自由的样式控制
            backgroundDismiss: false, // 禁止点击背景关闭
            theme: 'supervan', // 更显眼的主题风格
            buttons: {
              '⚠ 重新尝试': {
                btnClass: 'btn-red',
                action: () => {
                  this.handlePopoverClosed(); // 重新执行
                }
              }
            }
          });
        } else {
          // 设置为已读
          for (let i = 0; i < this.messages.length; i++) {
            this.messages[i].YDBZ = 1;
          }
        }
      }).catch(error => {
        console.log(error);
        $.confirm({
          title: '⚠️ 网络崩溃警告',
          content: `<div style="color:#b00020;font-weight:bold;font-size:16px;">
                更新消息状态失败（一般性故障）：
                <br><br>
                <code>${error.message}</code>
              </div>`,
          type: 'red',
          typeAnimated: true,
          boxWidth: '500px',
          useBootstrap: false, // 更自由的样式控制
          backgroundDismiss: false, // 禁止点击背景关闭
          theme: 'supervan', // 更显眼的主题风格
          buttons: {
            '⚠ 重新尝试': {
              btnClass: 'btn-red',
              action: () => {
                this.handlePopoverClosed(); // 重新执行
              }
            }
          }
        });
      });
    },
    formatDate(dateStr) {
      return dateStr ? new Date(dateStr).toLocaleString() : "-";
    },
    handlePageChange(page) {
      this.currentPage = page;
    },
    getIndexCount() {
      axios.get("/data/getUserIndexCount", {params: {YHM: this.UserInfo.username, YHSFDM: 1}}).then(response => {
        if (response.data.result) {
          this.IndexDataCount.XSS = response.data.data.XSS;
          this.IndexDataCount.RZDWS = response.data.data.RZDWS;
          this.IndexDataCount.YJYXSS = response.data.data.YJYXSS;
          this.IndexDataCount.JYL = response.data.data.JYL;
          this.IndexDataCount.YXGWS = response.data.data.YXGWS;
        } else {
          this.$message.error(response.data.msg);
        }
      }).catch(error => {
        this.$message.error('加载数据失败:' + error.message);
      });
    },
    getLoginUserInfo() {
      axios
          .get("/user/checkSession")
          .then((response) => {
            if (!response.data.result) {
              EventBus.$emit("show-auth-popup");
              setTimeout(() => {
                this.$router.push({name: "Login"});
              }, 1000);
            } else {
              this.UserInfo = {
                name: response.data.name,
                role: response.data.role,
                username: response.data.username,
              };
              this.getXxdm();
              this.getJobData();
              this.getIndexCount();
            }
          })
          .catch(() => {
            EventBus.$emit("show-auth-popup");
            setTimeout(() => {
              this.$router.push({name: "Login"});
            }, 1000);
          });
    },
    getXxdm() {
      axios
          .get(`/xxdmk/getXxdmk?YHM=${this.UserInfo.username}&YHSFDM=1`)
          .then((res) => {
            if (res.data.result) {
              this.messages = res.data.data.filter(
                  (m) => m.CFZ !== this.UserInfo.username
              );
            }
          })
          .catch(() => {
          });
    },
    // 获取当前用户发布的岗位--启用的
    getJobData() {
      axios.get("/dataGwdmk/getGwdmkDataToInterface", {
        params: {
          IsJustOne: 0,
          gwdm: 0,
          QYDM: 1,
          IsByFBZ: 0,
          FBZ: -1,
          SXBZ: 2,
          SHBZ: 1
        }
      }).then(res => {
        if (res.data.result) {
          this.DATAGWDMK = res.data.data
              .sort((a, b) => new Date(b.FBSJ) - new Date(a.FBSJ))
              .slice(0, 3);

        } else {
          this.$message.error('获取职位信息失败:' + res.data.msg);
        }
      }).catch(error => {
        this.$message.error('获取职位信息失败:' + error.message);
      });
    },
    // 专业学生分布图
    async initCharts() {
      // 各专业学生分布柱状图
      const majorCtx = document.getElementById('majorStudentsChart').getContext('2d');
      const ResponseData= await axios.get("/data/getAdminIndexZYTJData");
      if (ResponseData.data.result){
        let Xdata = [];
        let Ydata = [];
        let BackgroundColor = [];
        for(let i=0;i<ResponseData.data.data.length;i++){
          Xdata.push(ResponseData.data.data[i].ZYMC);
          Ydata.push(ResponseData.data.data[i].ZYRS);
          BackgroundColor.push('#'+Math.floor(Math.random()*16777215).toString(16));
        }new Chart(majorCtx, {
          type: 'bar',
          data: {
            labels: Xdata,
            datasets: [{
              label: '学生人数',
              data: Ydata,
              backgroundColor: BackgroundColor,
            }]
          },
          options: {
            responsive: true,
            plugins: {
              datalabels: {
                color: 'black',
                anchor: 'end',
                align: 'top',
                formatter: Math.round
              }
            }
          },
          plugins: [ChartDataLabels]
        });
      }else{
        this.$message.error('获取专业数据失败:' + ResponseData.data.msg);
      }


      // 就业行业分布饼图
      const industryCtx = document.getElementById('industryDistributionChart').getContext('2d');
      const ResponseData_DWHY= await axios.get("/data/getAdminIndexDwhyTJData");
      if (ResponseData_DWHY.data.result) {
        let Xdata = [];
        let Ydata = [];
        let BackgroundColor = [];
        for(let i=0;i<ResponseData_DWHY.data.data.length;i++){
          Xdata.push(ResponseData_DWHY.data.data[i].DWHY);
          Ydata.push(ResponseData_DWHY.data.data[i].HYSL);
          BackgroundColor.push('#'+Math.floor(Math.random()*16777215).toString(16));
        }
        new Chart(industryCtx, {
          type: 'pie',
          data: {
            labels: Xdata,
            datasets: [{
              data: Ydata,
              backgroundColor: BackgroundColor,
            }]
          },
          options: {
            responsive: true,
            plugins: {
              datalabels: {
                color: 'white',
                formatter: (value, ctx) => {
                  return `${ctx.chart.data.labels[ctx.dataIndex]}\n${value}%`;
                }
              }
            }
          },
          plugins: [ChartDataLabels]
        });
      }else{
        this.$message.error('获取就业行业数据失败:' + ResponseData_DWHY.data.msg);
      }

      const ResponseData_TDTJ = await axios.get(
          `/data/getTdtjData?YHM=${this.UserInfo.username}&YHSFDM=1&JsSeven=1`
      );
      if (ResponseData_TDTJ.data.result) {
        let Xdata = [];
        let Ydata = [];
        for (let i = 0; i < ResponseData_TDTJ.data.data.length; i++) {
          Xdata.push(ResponseData_TDTJ.data.data[i].day);
          Ydata.push(ResponseData_TDTJ.data.data[i].count);
        }

        // 学生投递记录信息
        const trendCtx = document.getElementById('employmentTrendChart').getContext('2d');
        new Chart(trendCtx, {
          type: 'line',
          data: {
            labels: Xdata,
            datasets: [{
              label: '投递人次',
              data: Ydata,
              borderColor: 'rgba(75, 192, 192, 1)',
              backgroundColor: 'rgba(75, 192, 192, 0.2)',
              tension: 0.4
            }]
          },
          options: {
            responsive: true,
            plugins: {
              datalabels: {
                color: 'black',
                anchor: 'end',
                align: 'top',
                formatter: Math.round
              }
            }
          },
          plugins: [ChartDataLabels]
        });

      }

      const  ResponseData_MsSex = await axios.get("/data/getAdminIndexStuMsData");
      if (ResponseData_MsSex.data.result) {
        let Xdata = [];
        let Ydata1 = [];
        let Ydata2 = [];
        for (let i = 0; i < ResponseData_MsSex.data.data.length; i++) {
          Xdata.push(ResponseData_MsSex.data.data[i].MSRQ);//面试日期
          Ydata1.push(ResponseData_MsSex.data.data[i].NSMSS);//男生面试数量
          Ydata2.push(ResponseData_MsSex.data.data[i].VSMSS); //女生面试数量
        }
        // 面试场次统计柱状图（堆叠）
        const interviewCtx = document.getElementById('interviewSessionsChart').getContext('2d');
        new Chart(interviewCtx, {
          type: 'bar',
          data: {
            labels: Xdata,
            datasets: [
              {
                label: '男生面试',
                data: Ydata1,
                backgroundColor: 'rgba(54, 162, 235, 0.6)'
              },
              {
                label: '女生面试',
                data: Ydata2,
                backgroundColor: 'rgba(255, 99, 132, 0.6)'
              }
            ]
          },
          options: {
            responsive: true,
            plugins: {
              datalabels: {
                color: 'black',
                anchor: 'end',
                align: 'top',
                formatter: Math.round
              }
            },
            scales: {
              x: {stacked: true},
              y: {stacked: true}
            }
          },
          plugins: [ChartDataLabels]
        });
      }else{
        this.$message.error('获取学生性别数据失败:' + ResponseData_MsSex.data.msg);
      }

    },
    markAsRead(message) {
      // 标记已读逻辑
      message.YDBZ = 1;
    },
  },
};
</script>

<style scoped>
/* 全局卡片阴影与边框 */
.shadow-sm {
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.hover\:shadow-md:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 消息通知样式 */
.notification-popover {
  padding: 0 !important;
}

.notification-container {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.message-card {
  position: relative;
  display: flex;
  align-items: center;
  padding: 10px;
  background: #fff;
  border-radius: 8px;
  transition: transform 0.3s, box-shadow 0.3s;
}

.message-content {
  flex: 1;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 0.9em;
}

.sender {
  font-weight: bold;
  color: #303133;
}

.time {
  color: #909399;
}

.message-content p {
  margin: 0;
  color: #606266;
}

.unread-dot {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 8px;
  height: 8px;
  background-color: red;
  border-radius: 50%;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.el-pager li {
  border-radius: 4px;
  transition: background-color 0.2s;
}

.el-pager li:hover {
  background-color: #ecf5ff;
}

.el-pager li.active {
  background-color: #409eff;
  color: #fff;
}

/* 其它深度样式保持不变 */
:deep(.el-card__header) {
  border-bottom: 0;
}
</style>
